package com.hz.basic.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hz.basic.component.Constant;
import com.hz.basic.entity.*;
import com.hz.basic.service.*;
import com.hz.common.utils.PageUtils;
import com.hz.common.utils.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.text.Collator;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("chinesebrush")
@Api(tags="软笔")
public class ChineseBrushController {

    @Autowired
    private CbBookEditionService bookEditionService;

    @Autowired
    private CbBookService bookService;

    @Autowired
    private CbContentsService cbContentsService;

    @Autowired
    private CbUnitService cbUnitService;

    @Autowired
    private CbChapterService chapterService;

    @Autowired
    private CbChapterPictureService chapterPictureService;

    @Autowired
    private CbTypefaceService typefaceService;

    @Autowired
    private CbAppreciationService appreciationService;

    @Autowired
    private CbAppreciationPictureService appreciationPictureService;

    @Autowired
    private CbReadingService readingService;

    @Autowired
    private CbReadingPictureService readingPictureService;

    @Autowired
    private CbObserveService observeService;

    @Autowired
    private CbObservePictureService observePictureService;

    @Autowired
    private CbBrushService brushService;

    @Autowired
    private CbStandardBrushService standardBrushService;

    @Autowired
    private CbBasisStrokesService basisStrokesService;

    @Autowired
    private CbAnalyzeService analyzeService;

    @Autowired
    private CbContrastService contrastService;

    @Autowired
    private CbContrastTypefaceService contrastTypefaceService;

    @Autowired
    private CbPracticeService practiceService;

    @Autowired
    private CbTypefacePositionService cbTypefacePositionService;

    @Autowired
    private CbFixUnitService cbFixUnitService;

    @Autowired
    private CbFixChapterService cbFixChapterService;

    @Autowired
    private CbFixChapterTypefaceService cbFixChapterTypefaceService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    private CbExpandEditionService cbExpandEditionService;

    @Autowired
    private CbExpandResourceClassificationService cbERClassificationService;

    @Autowired
    private CbExpandResourceService cbExpandResourceService;

    @ApiOperation("获取七步按钮")
    @GetMapping("/getbutton")
    @ApiImplicitParam(name = "tid", value = "生字id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<List<String>> getbutton(@RequestParam("tid") Long tid){
        List<String> buttonList = new ArrayList<>();
        CbTypefaceEntity typeface = typefaceService.getById(tid);
        List<CbAppreciationEntity> appreciations = appreciationService.list(new QueryWrapper<CbAppreciationEntity>().eq("tid", tid));
        List<CbReadingEntity> readings = readingService.list(new QueryWrapper<CbReadingEntity>().eq("tid", tid));
        List<CbObserveEntity> observes = observeService.list(new QueryWrapper<CbObserveEntity>().eq("tid", tid));
        List<CbAnalyzeEntity> analyzes = analyzeService.list(new QueryWrapper<CbAnalyzeEntity>().eq("tid", tid));
        List<CbBrushEntity> brushs = brushService.list(new QueryWrapper<CbBrushEntity>().eq("tid", tid));
        List<CbContrastEntity> contrasts = contrastService.list(new QueryWrapper<CbContrastEntity>().eq("tid", tid));
        List<CbPracticeEntity> practices = practiceService.list(new QueryWrapper<CbPracticeEntity>().eq("tid", tid));
        if (appreciations.size() > 0)   buttonList.add("欣赏");
        if (readings.size() > 0)   buttonList.add("认读");
        if (observes.size() > 0)   buttonList.add("观察");
        if (analyzes.size() > 0)   buttonList.add("分析");
        if (brushs.size() > 0)   buttonList.add("笔法");
        if (typeface.getVideo() != null)    buttonList.add("视频");
        if (contrasts.size() > 0)   buttonList.add("对比");
        if (practices.size() > 0)   buttonList.add("随堂练习");
        return ResponseData.success(buttonList);
    }

    @ApiOperation("获取基本笔画模板资源包")
    @GetMapping("/getbasisstrokesformworkzip")
    public ResponseData<FixedInformationDicEntity> getbasisstrokesformworkzip(){
        FixedInformationDicEntity basisStrokesFormwork = bookService.getFixedInformation(Constant.ZipBasisStrokes.ZIPNAME.getName());
        if(basisStrokesFormwork == null){
            return ResponseData.success("资源包未上传");
        }
        return ResponseData.success(basisStrokesFormwork);
    }

    @ApiOperation("获取标准笔法模板资源包")
    @GetMapping("/getstandardbrushzip")
    public ResponseData<FixedInformationDicEntity> getstandardbrushzip(){
        FixedInformationDicEntity standardBrush = bookService.getFixedInformation(Constant.ZipStandardBrush.ZIPNAME.getName());
        if(standardBrush == null){
            return ResponseData.success("资源包未上传");
        }
        return ResponseData.success(standardBrush);
    }

    @ApiOperation("软笔书扩展资源分类")
    @GetMapping("/getbookeditionclassification")
    @ApiImplicitParam(name = "eid", value = "扩展版本id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<List<CbExpandResourceClassificationEntity>> getbookeditionclassification(@RequestParam("eid") Long eid){
        List<CbExpandResourceClassificationEntity> expandEditionResourceClassifications = cbERClassificationService.list(new QueryWrapper<CbExpandResourceClassificationEntity>().eq("eid",eid).orderByAsc("corder"));
        return ResponseData.success(expandEditionResourceClassifications);
    }

    @ApiOperation("软笔书扩展版本资源")
    @GetMapping("/getexpandresource")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cid", value = "分类id，012分别查询（0：碑帖欣赏1：国学经典2：书法知识）所有资源", paramType = "query", dataType = "Long", required = true),
            @ApiImplicitParam(name = "condition", value = "查询条件", paramType = "query", dataType = "String", required = false),
            @ApiImplicitParam(name = "curpage", value = "分页，当前页", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "numpage", value = "分页，页数量", paramType = "query", dataType = "int", required = true)
    })
    public ResponseData<PageUtils> getexpandresource(@RequestParam("cid") Long cid,@RequestParam(name = "condition",required = false) String condition
            ,@RequestParam(name = "curpage") int curpage,@RequestParam(name = "numpage") int numpage) {
        PageUtils page;
        if (cid == 0 || cid == 1 || cid == 2)
            page = cbExpandResourceService.getallexpandresource(cid,condition,curpage,numpage);
        else page = cbExpandResourceService.getexpandresource(cid,condition,curpage,numpage);
        return ResponseData.success(page);
    }

    @ApiOperation("软笔书版本")
    @GetMapping("/getbookedition")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization",value = "token",paramType = "header",dataType = "String",required = true),
            @ApiImplicitParam(name = "GetCompressPackage",value = "获取压缩包否，（1：是，其他或为空：否）",paramType = "header",dataType = "Long",required = false)
    })
    public ResponseData<List<CbBookEditionEntity>> getbookedition(@RequestHeader("Authorization") String token, @RequestHeader(value = "GetCompressPackage",required = false) Long GetCompressPackage){
        long userId = Long.parseLong(redisTemplate.opsForValue().get("user:" + token));
        List<CbBookEditionEntity> bookEditions = bookEditionService.getbookedition(userId);
        List<CbBookEditionEntity> bookExpandEditions = cbExpandEditionService.getbookexpandedition(userId);
        for (CbBookEditionEntity bookEditionEntity : bookExpandEditions)
            bookEditions.add(bookEditionEntity);
        // 若是获取压缩包去除特定版本
        bookEditions.removeIf(bookEdition -> (GetCompressPackage != null && GetCompressPackage == 1 && judgeGetCompressPackageEdition(bookEdition.getEditionName())));
        Collections.sort(bookEditions, Comparator.comparing(CbBookEditionEntity::getOrder));
        return ResponseData.success(bookEditions);
    }

    /**
     * 获取压缩包的软笔版本时判断是否是移除的版本（不显示在获取压缩包的列表）
     * @return
     */
    private boolean judgeGetCompressPackageEdition(String editionName){
        switch (editionName) {
            case "陕西科技":
            case "福建美术":
            case "通用版":
            case "碑帖欣赏":
            case "书法知识":
            case "国学经典":
                return true;
        }
        return false;
    }
    @ApiOperation("软笔书")
    @GetMapping("/getbookbyeid")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "eid", value = "书本版本id", paramType = "query", dataType = "Long", required = true),
            @ApiImplicitParam(name = "Authorization",value = "token",paramType = "header",dataType = "String",required = true)
    })
    public ResponseData<List<CbBookEntity>> getbookbyeid(@RequestParam("eid") Long eid, @RequestHeader("Authorization") String token){
        long userId = Long.parseLong(redisTemplate.opsForValue().get("user:" + token));
        List<CbBookEntity> books = bookService.getBookList(userId,eid);
        return ResponseData.success(books);
    }

    @ApiOperation("通用版获取软笔书")
    @GetMapping("/getcommonbookbycondition")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "eid", value = "书本版本id", paramType = "query", dataType = "Long", required = true),
            @ApiImplicitParam(name = "classify", value = "软笔书分类", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "title", value = "软笔书标签", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "Authorization",value = "token",paramType = "header",dataType = "String",required = true)
    })
    public ResponseData<List<CbBookEntity>> getcommonbookbycondition(@RequestParam("eid") Long eid,
                                                                     @RequestParam("classify") String classify,
                                                                     @RequestParam("title") String title,
                                                                     @RequestHeader("Authorization") String token){
        long userId = Long.parseLong(redisTemplate.opsForValue().get("user:" + token));
        List<CbBookEntity> books = bookService.getCommonBookList(userId,eid,classify,title);
        return ResponseData.success(books);
    }

    @ApiOperation("获取目录")
    @GetMapping("/getcontentsbybid")
    @ApiImplicitParam(name = "bid", value = "软笔书id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<List<CbContentsEntity>> getcontentsbybid(@RequestParam("bid") Long bid){
        List<CbContentsEntity> contents = cbContentsService.list(new QueryWrapper<CbContentsEntity>().eq("bid", bid));
        for (CbContentsEntity content:contents) {
            List<CbUnitEntity> units = cbUnitService.list(new QueryWrapper<CbUnitEntity>().eq("cid",content.getId()));
            for (CbUnitEntity unit:units) {
                List<CbChapterEntity> chapters = chapterService.list(new QueryWrapper<CbChapterEntity>().eq("uid",unit.getId()).orderByAsc("corder"));
                unit.setChapters(chapters);
            }
            content.setUnits(units);
        }
        return ResponseData.success(contents);
    }

    @ApiOperation("获取固定目录")
    @GetMapping("/getfixcontentsbybid")
    @ApiImplicitParam(name = "bid", value = "软笔书id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<List<CbFixUnitEntity>> getfixcontentsbybid(@RequestParam("bid") Long bid){
        List<CbFixUnitEntity> units = cbFixUnitService.list(new QueryWrapper<CbFixUnitEntity>().eq("bid", bid));
        for (CbFixUnitEntity unit:units) {
            List<CbFixChapterEntity> fixChapters = cbFixChapterService.list(new QueryWrapper<CbFixChapterEntity>().eq("uid",unit.getId()));
            unit.setFixChapters(fixChapters);
        }
        return ResponseData.success(units);
    }

    @ApiOperation("获取固定章节下字体")
    @GetMapping("/getfixcontentstypefacesbycid")
    @ApiImplicitParam(name = "cid", value = "固定章节id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<List<CbTypefaceEntity>> getfixcontentstypefacesbycid(@RequestParam("cid") Long cid){
        List<CbTypefaceEntity> typefaces = cbFixChapterTypefaceService.getTypefaceByCid(cid);
        return ResponseData.success(typefaces);
    }

    @ApiOperation("每章节内容")
    @GetMapping("/getchappicbycid")
    @ApiImplicitParam(name = "cid", value = "章节id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<List<CbChapterPictureEntity>> getchappicbypid(@RequestParam("cid") Long cid){
        List<CbChapterPictureEntity> chapterPictures = chapterPictureService.list(new QueryWrapper<CbChapterPictureEntity>().eq("cid",cid));
        for (CbChapterPictureEntity chapterPicture:chapterPictures) {
            List<CbTypefacePositionEntity> typefacePositions = cbTypefacePositionService.list(new QueryWrapper<CbTypefacePositionEntity>().eq("pid",chapterPicture.getId()));
            chapterPicture.setTypefacePositions(typefacePositions);
        }
        return ResponseData.success(chapterPictures);
    }

    @ApiOperation("视频")
    @GetMapping("/getvideobytid")
    @ApiImplicitParam(name = "tid", value = "字体id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<CbVideoEntity> getvideobytid(@RequestParam("tid") Long tid){
        CbVideoEntity typeface = typefaceService.getvideobytid(tid);
        return ResponseData.success(typeface);
    }

    @ApiOperation("欣赏")
    @GetMapping("/getappreciationbytid")
    @ApiImplicitParam(name = "tid", value = "字体id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<List<CbAppreciationEntity>> getappreciationbytid(@RequestParam("tid") Long tid){
        List<CbAppreciationEntity> appreciationEntities = appreciationService.list(new QueryWrapper<CbAppreciationEntity>().eq("tid", tid));
        for (CbAppreciationEntity appreciationEntity:appreciationEntities){
            List<CbAppreciationPictureEntity> list = appreciationPictureService.list(new QueryWrapper<CbAppreciationPictureEntity>().eq("pid", appreciationEntity.getId()));
            appreciationEntity.setPiclist(list);
        }
        return ResponseData.success(appreciationEntities);
    }

    @ApiOperation("认读")
    @GetMapping("/getreadingbytid")
    @ApiImplicitParam(name = "tid", value = "字体id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<CbReadingEntity> getreadingbytid(@RequestParam("tid") Long tid){
        CbReadingEntity readingEntity = readingService.getOne(new QueryWrapper<CbReadingEntity>().eq("tid", tid).last("limit 1"));
        List<CbReadingPictureEntity> list = null;
        if (readingEntity!=null)
            list = readingPictureService.list(new QueryWrapper<CbReadingPictureEntity>().eq("pid", readingEntity.getId()).orderByAsc("porder"));
        readingEntity.setPiclist(list);
        return ResponseData.success(readingEntity);
    }

    @ApiOperation("观察")
    @GetMapping("/getobservebytid")
    @ApiImplicitParam(name = "tid", value = "字体id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<CbObserveEntity> getobservebytid(@RequestParam("tid") Long tid){
        CbObserveEntity observeEntity = observeService.getOne(new QueryWrapper<CbObserveEntity>().eq("tid", tid).last("limit 1"));
        List<CbObservePictureEntity> list = null;
        if (observeEntity!=null)
            list = observePictureService.list(new QueryWrapper<CbObservePictureEntity>().eq("pid", observeEntity.getId()).orderByAsc("porder"));
        observeEntity.setPiclist(list);
        return ResponseData.success(observeEntity);
    }

    @ApiOperation("笔法")
    @GetMapping("/getbrushbytid")
    @ApiImplicitParam(name = "tid", value = "字体id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<CbBrushEntity> getbrushbytid(@RequestParam("tid") Long tid){
        CbBrushEntity brushEntity = brushService.getOne(new QueryWrapper<CbBrushEntity>().eq("tid", tid).last("limit 1"));
        List<CbStandardBrushEntity> standardBrushList = standardBrushService.list(new QueryWrapper<CbStandardBrushEntity>().orderByAsc("sorder"));
        List<CbBasisStrokesEntity> basisStrokesList = null;
        if (brushEntity != null) {
            basisStrokesList = basisStrokesService.getJbbhListByTid(tid);
        }
        brushEntity.setStandardBrushList(standardBrushList);
        brushEntity.setBasisStrokesList(basisStrokesList);
        return ResponseData.success(brushEntity);
    }

    @ApiOperation("分析")
    @GetMapping("/getanalyzebytid")
    @ApiImplicitParam(name = "tid", value = "字体id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<CbAnalyzeEntity> getanalyzebytid(@RequestParam("tid") Long tid){
        CbAnalyzeEntity analyzeEntity = analyzeService.getOne(new QueryWrapper<CbAnalyzeEntity>().eq("tid", tid).last("limit 1"));
        return ResponseData.success(analyzeEntity);
    }

    @ApiOperation("对比")
    @GetMapping("/getcontrastbytid")
    @ApiImplicitParam(name = "tid", value = "字体id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<CbContrastEntity> getcontrastbytid(@RequestParam("tid") Long tid){
        CbContrastEntity contrastEntity = contrastService.getOne(new QueryWrapper<CbContrastEntity>().eq("tid", tid).last("limit 1"));
        List<CbContrastTypefaceEntity> list = null;
        if (contrastEntity!=null)
            list = contrastTypefaceService.list(new QueryWrapper<CbContrastTypefaceEntity>().eq("cid", contrastEntity.getId()).orderByAsc("corder"));
        contrastEntity.setContrastTypefaces(list);
        return ResponseData.success(contrastEntity);
    }

    @ApiOperation("随堂练习")
    @GetMapping("/getpracticebytid")
    @ApiImplicitParam(name = "tid", value = "字体id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<CbPracticeEntity> getpracticebytid(@RequestParam("tid") Long tid){
        CbPracticeEntity practiceEntity = practiceService.getOne(new QueryWrapper<CbPracticeEntity>().eq("tid", tid).last("limit 1"));
        return ResponseData.success(practiceEntity);
    }

    @ApiOperation("软笔书按条件检索字")
    @GetMapping("/gettypefacesbycondition")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "characters", value = "字库类别", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "content", value = "搜索框内容", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "curpage", value = "分页，当前页", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "numpage", value = "分页，页数量", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "Authorization",value = "token",paramType = "header",dataType = "String",required = true)
    })
    public ResponseData<PageUtils<List<CbTypefaceEntity>>> gettypefacesbycondition(@RequestParam("characters") String characters,
                                                                                      @RequestParam("content") String content,
                                                                                      @RequestParam("curpage") int curpage,
                                                                                      @RequestParam("numpage") int numpage,
                                                                                      @RequestHeader("Authorization") String token){
        long userId = Long.parseLong(redisTemplate.opsForValue().get("user:" + token));
        PageUtils<List<CbTypefaceEntity>> page = typefaceService.gettypefacesbycondition(characters, content.trim(), curpage, numpage);
        return ResponseData.success(page);
    }
}
